package com.cloud.gateway.handler;


import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashSet;
import java.util.Iterator;

@Component
public class RouteXmlHandler {

    private static final Logger log = LoggerFactory.getLogger(RouteXmlHandler.class);

    private String routePath = "route.xml";

    private HashSet<String> actionUrls = new HashSet<String>();

    public HashSet<String> getActionUrls() {
        return actionUrls;
    }

    /**
     * 读取route.xml 需要进行登录验证的路由信息
     */
    public void readXml() {
        try {
            ClassPathResource classPathResource = new ClassPathResource(routePath);
            InputStream inputStream =classPathResource.getInputStream();

            //1.创建Reader对象
            SAXReader reader = new SAXReader();
            //2.加载xml
            Document document = reader.read(inputStream);
            //3.获取根节点
            Element rootElement = document.getRootElement();

            Iterator iterator = rootElement.elementIterator();
            while (iterator.hasNext()){
                Element stu = (Element) iterator.next();
                //遍历子节点
                Iterator iterator1 = stu.elementIterator();
                while (iterator1.hasNext()){
                    Element stuChild = (Element) iterator1.next();
                    this.actionUrls.add(stuChild.getStringValue());
                }
            }

            for (String actUrl:actionUrls)
            {
                log.info("actUrl:" + actUrl);
            }

        } catch (DocumentException | IOException e)
        {
            e.printStackTrace();

            log.info("RouteXml:" + e.getMessage());
        }

    }

}
